package com.carlinfo.back.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.servlet.BaseServlet;
import com.carlinfo.common.util.PageInfoUtil;
import com.carlinfo.userscenter.stu.pojo.Answer;
import com.carlinfo.userscenter.stu.pojo.Level;
import com.carlinfo.userscenter.stu.pojo.Question;
import com.carlinfo.userscenter.stu.pojo.Students;
import com.carlinfo.userscenter.stu.service.IQuestionService;
import com.carlinfo.userscenter.stu.service.IStudentService;
import com.carlinfo.userscenter.stu.service.impl.QuestionServiceImpl;
import com.carlinfo.userscenter.stu.service.impl.StudentServiceImpl;


public class StudentBackServlet extends BaseServlet
{
	IStudentService studentService = new StudentServiceImpl();
	IQuestionService questionService = new QuestionServiceImpl();
	

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		this.logger.info("===========DemoBackServlet===========");
		String param = request.getParameter("method");
		if ("studentList".equalsIgnoreCase(param))
		{
			this.studentList(request, response);
		} else if ("levelList".equalsIgnoreCase(param))
		{
			this.levelList(request, response);
		} else if ("questionList".equalsIgnoreCase(param))
		{
			this.questionList(request, response);
		} else if ("answerList".equalsIgnoreCase(param))
		{
			this.answerList(request, response);
		} else if ("questionInsert".equalsIgnoreCase(param))
		{
			this.questionInsert(request, response);
		} else if ("questionInsertSubmit".equalsIgnoreCase(param))
		{
			this.questionInsertSubmit(request, response);
		} else if ("studentsInsert".equalsIgnoreCase(param))
		{
			this.studentsInsert(request, response);
		} else if ("studentsInsertSubmit".equalsIgnoreCase(param))
		{
			this.studentsInsertSubmit(request, response);
		}  else if ("studentsUpdate".equalsIgnoreCase(param))
		{
			this.studentsUpdate(request, response);
		}else if ("studentsUpdateSubmit".equalsIgnoreCase(param))
		{
			this.studentsUpdateSubmit(request, response);
		}else if ("gameList".equalsIgnoreCase(param))
		{
			this.gameList(request, response);
		} else if ("gameSubmit".equalsIgnoreCase(param))
		{
			this.gameSubmit(request, response);
		} else if ("gameStartSubmit".equalsIgnoreCase(param))
		{
			this.gameStartSubmit(request, response);
		} else if ("answerInsertSubmit".equalsIgnoreCase(param))
		{
			this.answerInsertSubmit(request, response);
		} else if ("select".equalsIgnoreCase(param))
		{
			this.select(request, response);
		} else if ("answerselect".equalsIgnoreCase(param))
		{
			this.answerselect(request, response);
		}else if ("chouJiang".equalsIgnoreCase(param))
		{
			this.chouJiang(request, response);
		}
		
	}
	
	
	private void studentsUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String,Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		//condMap.put("name", "大明");
		Students students = this.studentService.selectOneStudentsService(condMap);
		if(students != null)
		{
			/* 从jsp中获取 */
			String name = request.getParameter("name");
			String sex = request.getParameter("sex");
			String birth = request.getParameter("birth");
			String graduateSchool = request.getParameter("graduateSchool");
			String createTime = request.getParameter("createTime");
//			String updateTime = request.getParameter("updateTime");
			String pubTime = request.getParameter("pubTime");
			String status = request.getParameter("status");
			String context = request.getParameter("Context");
			
			/* new出来的,属性有值? */
			students.setName(name);
			students.setSex(sex);
			students.setBirth(this.dateUtil.strToDate(birth));
			students.setGraduateSchool(graduateSchool);
			students.setCreateTime(this.dateUtil.strToDate(createTime));
			students.setUpdateTime(new Date());
			students.setPubTime(this.dateUtil.strToDate(pubTime));
			students.setStatus(Byte.valueOf(status));
			students.setContext(context);
			
			/* 保存一条记录 */
			JSONObject resultJSON = this.studentService.updateOneStudentsService(students);
			this.logger.info("返回值:{}",resultJSON);
			
			/* 往request中放的是json */
			request.setAttribute("resultJSON", resultJSON);
			/* 保存成功,又跳转到朝代添加的jsp中 */
			List<Students> studentList = this.studentService.selectListStudentsService(null, condMap);
			request.setAttribute("studentList", studentList);
			
			String path = "/WEB-INF/jsp/back/user/studentsList.jsp";
			request.getRequestDispatcher(path).forward(request, response);
		}
	
	}


	private void studentsUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.logger.info("--DemoBackServlet--studentsUpdate--");
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		Map<String, Object> condMap = new HashMap<String, Object>() ;
		/* 根据id查询 */
		condMap.put("id", id);
		//condMap.put("name", "大明");
		Students students = this.studentService.selectOneStudentsService(condMap);
		/* 赶紧将查询的结果放到四大作用域(request中) */
		request.setAttribute("students", students);
	
		/* 服务器端跳转:
		 * 为啥要跳转:因为写html回信,jsp善长 */
		String path = "/WEB-INF/jsp/back/user/studentsUpdate.jsp" ; 
		request.getRequestDispatcher(path).forward(request, response);
	
	}
	private void studentsInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.logger.info("--DemoBackServlet--studentsInsertSubmit--");
		/* 从jsp中获取 */
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String birth = request.getParameter("birth");
		String graduateSchool = request.getParameter("graduateSchool");
		String createTime = request.getParameter("createTime");
		String updateTime = request.getParameter("updateTime");
		String pubTime = request.getParameter("pubTime");
		String status = request.getParameter("status");
		String context = request.getParameter("Context");
		
		/* new出来的,属性有值? */
		Students students = new Students() ; 
		students.setName(name);
		students.setSex(sex);
		students.setBirth(this.dateUtil.strToDate(birth));
		students.setGraduateSchool(graduateSchool);
		students.setCreateTime(this.dateUtil.strToDate(createTime));
		students.setUpdateTime(this.dateUtil.strToDate(updateTime));
		students.setPubTime(this.dateUtil.strToDate(pubTime));
		students.setStatus(Byte.valueOf(status));
		students.setContext(context);
		/* 保存一条记录 */
		JSONObject resultJSON = this.studentService.saveOneStudentsService(students);
		this.logger.info("返回值:{}",resultJSON);
		
		/* 往request中放的是json */
		request.setAttribute("resultJSON", resultJSON);
		/* 保存成功,又跳转到朝代添加的jsp中 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		List<Students> studentList = this.studentService.selectListStudentsService(null, condMap);
		request.setAttribute("studentList", studentList);
		
		String path = "/WEB-INF/jsp/back/user/studentsList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}


	private void studentsInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/user/studentsInsert.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}


	private void chouJiang(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html;charset=UTF-8");
//		response.setCharacterEncoding("UTF-8");
		int score = Integer.valueOf(request.getParameter("score"));
		int questionId = Integer.valueOf(request.getParameter("id"));
		HttpSession session = request.getSession();
		session.setAttribute("score", score);
		session.setAttribute("questionId", questionId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", questionId);
		/* 抽到了一个问题 */
		Question question = this.questionService.selectOneQuestionService(map);
//		System.out.println(question.getName());
		if (question != null)
		{
			request.setAttribute("question", question);

			String path = "/WEB-INF/jsp/back/user/gameStart.jsp";
			request.getRequestDispatcher(path).forward(request, response);
		}

		String info = "不存在这个问题";
		request.setAttribute("info", info);
		String path = "/WEB-INF/jsp/back/user/gameList.jsp";
		request.getRequestDispatcher(path).forward(request, response);

	}


	private void answerselect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		//condMap.put("name", "大明");
		
		Answer answer = this.questionService.selectOneAnswerService(condMap);
		System.out.println("========"+answer.getStudents().getName());
		/* 赶紧将查询的结果放到四大作用域(request中) */
		request.setAttribute("answer", answer);
		
		/* 服务器端跳转:
		 * 为啥要跳转:因为写html回信,jsp善长 */
		String path = "/WEB-INF/jsp/back/user/answerUpdate.jsp" ; 
		request.getRequestDispatcher(path).forward(request, response);
	}


	private void select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		//condMap.put("name", "大明");
		
		
		Question question = this.questionService.selectOneQuestionService(condMap);
		/* 赶紧将查询的结果放到四大作用域(request中) */
		request.setAttribute("question", question);
		
		/* 服务器端跳转:
		 * 为啥要跳转:因为写html回信,jsp善长 */
		String path = "/WEB-INF/jsp/back/user/questionUpdate.jsp" ; 
		request.getRequestDispatcher(path).forward(request, response);
	}


	/**
	 * 保存一条答案
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void answerInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String info ="";
		HttpSession session = request.getSession();
		Students students = (Students) session.getAttribute("lastStu");
		int score = Integer.valueOf(session.getAttribute("score") + "");
		int questionId = Integer.valueOf(session.getAttribute("questionId") + "");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", questionId);
		Question question = this.questionService.selectOneQuestionService(map);
		request.setAttribute("question", question);
		request.setAttribute("score", score);
		request.setAttribute("students", students);
//		this.logger.info("我才是你想要的问题:{}", question.getName());
//		this.logger.info("我才是你想要的答案:{}", request.getParameter("answer"));
//		this.logger.info("我才是你想要的分数:{}", request.getParameter("myScore"));
		
		double lastScore = Double.valueOf(request.getParameter("myScore") + "");
		String jieGuo = request.getParameter("answer") + "";
		
		byte status = Byte.valueOf(request.getParameter("status") + "");
		
		
		Answer answer = new Answer();
		answer.setJieGuo(jieGuo);
//		System.out.println("这个学生的答案是:"+status);
//		System.out.println("1".equalsIgnoreCase(status + ""));
		answer.setShiFou("1".equalsIgnoreCase(status + "") ? true : false);
		answer.setCreateTime(new Date());
		answer.setEndTime(new Date());
		answer.setQuestionId(question.getId());
		answer.setStuId(students.getId());
		answer.setPubTime(new Date());
		answer.setStatus(Byte.valueOf("1"));
//		System.out.println(score+"==="+question.getScore());
		/**
		 * 分数大于最大分数的时候,就加最大分数.
		 */
		if (lastScore > question.getScore())
		{
			students.setScore(students.getScore()+question.getScore());
		} else
		{
			students.setScore(students.getScore()+lastScore);
		}
		/* 更新分数以后更新学生 */
		this.studentService.updateOneStudentsService(students);
		JSONObject jsonObj = this.questionService.saveOneAnswerService(answer);
		request.setAttribute("info", jsonObj.get("info"));
		String path = "/WEB-INF/jsp/back/user/gameStart.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	/* 抽学生 */
	private void gameStartSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		List<Students> studentList = new ArrayList<Students>();
		Students students = null;
		String info = "";
		
		Random random = new Random();
		System.out.println("==========抽的学生如下============");
		while (true)
		{
			int tempId = random.nextInt(this.studentService.selectMaxIdService()) + 1;
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", tempId);
			students = this.studentService.selectOneStudentsService(condMap);
			studentList.add(students);
			System.out.println(students);
			if (this.studentService.askIsStudentService(students))
			{
				info = "恭喜你中奖了！";
				session.setAttribute("lastStu", students);
//				System.out.println("hello");
				response.setCharacterEncoding("UTF-8");
				String name = students.getName();
				JSONObject json = new JSONObject();
				json.put("name", name);
				json.put("id", students.getId());
				response.setCharacterEncoding("UTF-8");
				PrintWriter writer = response.getWriter();
				writer.println(json);
				writer.flush();
				writer.close();		
				break;
			}
		}
	}

	
	private void gameSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setContentType("text/html;charset=UTF-8");
//		response.setCharacterEncoding("UTF-8");
		int score = Integer.valueOf(request.getParameter("score"));
		int questionId = Integer.valueOf(request.getParameter("questionId"));
		HttpSession session = request.getSession();
		session.setAttribute("score", score);
		session.setAttribute("questionId", questionId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", questionId);
		Question question = this.questionService.selectOneQuestionService(map);

		if (question != null)
		{
			request.setAttribute("question", question);

			String path = "/WEB-INF/jsp/back/user/gameStart.jsp";
			request.getRequestDispatcher(path).forward(request, response);
		}

		String info = "不存在这个问题";
		request.setAttribute("info", info);
		String path = "/WEB-INF/jsp/back/user/gameList.jsp";
		request.getRequestDispatcher(path).forward(request, response);

	}

	private void gameList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		Map<String, Object> condMap = new HashMap<String,Object>();
		List<Students> studentList = this.studentService.selectListStudentsService(null, condMap);
		List<String> list = new ArrayList<String>();
		for (Students student : studentList)
		{
			list.add(student.getName());
		}
		request.setAttribute("list", list);
		for (String string : list)
		{
			System.out.println("=="+string+"==");
		}
		String path = "/WEB-INF/jsp/back/user/gameList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void questionInsertSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setContentType("text/html;charset=UTF-8");
		/* 将页面中的值取出来,添加朝代 */
		int score = Integer.valueOf(request.getParameter("score"));
		String name = request.getParameter("name");
		byte status = Byte.valueOf(request.getParameter("status"));

		Question question = new Question();
		question.setName(name);
		question.setScore(score);
		question.setStatus(status);
		question.setEndTime(new Date());
		question.setPubTime(new Date());
		question.setCreateTime(new Date());
		JSONObject jsonObj = this.questionService.saveOneQuestionService(question);
		logger.info("我保存了一条:{}", jsonObj.toJSONString());
		request.setAttribute("jsonObj", jsonObj);
		/* 保存成功继续跳转到原来的界面上去 */
		this.questionInsert(request, response);
	}

	private void questionInsert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/user/questionInsert.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void answerList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 取出查询条件 */
		String status = request.getParameter("status");
		String keyWord = request.getParameter("keyWord");
		String stTime = request.getParameter("stTime");
		String edTime = request.getParameter("edTime");

		if (keyWord == null)
		{
			keyWord = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (stTime == null)
		{
			stTime = "";
		}
		if (edTime == null)
		{
			edTime = "";
		}
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyWord", keyWord);
		condMap.put("status", status);

		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(stTime) && !"".equalsIgnoreCase(edTime))
		{
			stDate = this.dateUtil.strToDateTime(stTime);
			edDate = this.dateUtil.strToDateTime(edTime);
		}

		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);

//		List<ADynasty> dynastyList = this.demoService.selectListDynastyService(pageInfoUtil, condMap);
		System.out.println("我要工作了======================");
		List<Answer> answerList = this.questionService.selectListAnswerService(pageInfoUtil, condMap);
		request.setAttribute("answerList", answerList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);

		request.setAttribute("currentPage", pageInfoUtil.getCurrentPage());
		request.setAttribute("pageSize", pageInfoUtil.getPageSize());

		request.setAttribute("keyWord", keyWord);
		request.setAttribute("status", status);
		request.setAttribute("stTime", stTime);
		request.setAttribute("edTime", edTime);

		String path = "/WEB-INF/jsp/back/user/answerList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void questionList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 取出查询条件 */
		String status = request.getParameter("status");
		String keyWord = request.getParameter("keyWord");
		String stTime = request.getParameter("stTime");
		String edTime = request.getParameter("edTime");

		if (keyWord == null)
		{
			keyWord = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (stTime == null)
		{
			stTime = "";
		}
		if (edTime == null)
		{
			edTime = "";
		}
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyWord", keyWord);
		condMap.put("status", status);

		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(stTime) && !"".equalsIgnoreCase(edTime))
		{
			stDate = this.dateUtil.strToDateTime(stTime);
			edDate = this.dateUtil.strToDateTime(edTime);
		}

		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);

//		List<ADynasty> dynastyList = this.demoService.selectListDynastyService(pageInfoUtil, condMap);
		List<Question> questionList = this.questionService.selectListQuestionService(pageInfoUtil, condMap);
		request.setAttribute("questionList", questionList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);

		request.setAttribute("currentPage", pageInfoUtil.getCurrentPage());
		request.setAttribute("pageSize", pageInfoUtil.getPageSize());

		request.setAttribute("keyWord", keyWord);
		request.setAttribute("status", status);
		request.setAttribute("stTime", stTime);
		request.setAttribute("edTime", edTime);

		String path = "/WEB-INF/jsp/back/user/questionList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void levelList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 取出查询条件 */
		String status = request.getParameter("status");
		String keyWord = request.getParameter("keyWord");
		String stTime = request.getParameter("stTime");
		String edTime = request.getParameter("edTime");

		if (keyWord == null)
		{
			keyWord = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (stTime == null)
		{
			stTime = "";
		}
		if (edTime == null)
		{
			edTime = "";
		}
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyWord", keyWord);
		condMap.put("status", status);

		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(stTime) && !"".equalsIgnoreCase(edTime))
		{
			stDate = this.dateUtil.strToDateTime(stTime);
			edDate = this.dateUtil.strToDateTime(edTime);
		}

		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);

//		List<ADynasty> dynastyList = this.demoService.selectListDynastyService(pageInfoUtil, condMap);
		List<Level> levelList = this.studentService.selectListLevelService(pageInfoUtil, condMap);
		request.setAttribute("levelList", levelList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);

		request.setAttribute("currentPage", pageInfoUtil.getCurrentPage());
		request.setAttribute("pageSize", pageInfoUtil.getPageSize());

		request.setAttribute("keyWord", keyWord);
		request.setAttribute("status", status);
		request.setAttribute("stTime", stTime);
		request.setAttribute("edTime", edTime);

		String path = "/WEB-INF/jsp/back/user/levelList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void studentList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 取出查询条件 */
		String status = request.getParameter("status");
		String keyWord = request.getParameter("keyWord");
		String stTime = request.getParameter("stTime");
		String edTime = request.getParameter("edTime");

		if (keyWord == null)
		{
			keyWord = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (stTime == null)
		{
			stTime = "";
		}
		if (edTime == null)
		{
			edTime = "";
		}
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyWord", keyWord);
		condMap.put("status", status);

		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(stTime) && !"".equalsIgnoreCase(edTime))
		{
			stDate = this.dateUtil.strToDateTime(stTime);
			edDate = this.dateUtil.strToDateTime(edTime);
		}

		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);

//		List<ADynasty> dynastyList = this.demoService.selectListDynastyService(pageInfoUtil, condMap);
		List<Students> studentList = this.studentService.selectListStudentsService(pageInfoUtil, condMap);
		request.setAttribute("studentList", studentList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);

		request.setAttribute("currentPage", pageInfoUtil.getCurrentPage());
		request.setAttribute("pageSize", pageInfoUtil.getPageSize());

		request.setAttribute("keyWord", keyWord);
		request.setAttribute("status", status);
		request.setAttribute("stTime", stTime);
		request.setAttribute("edTime", edTime);

		String path = "/WEB-INF/jsp/back/user/studentsList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}
}
